from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from user.models import *
from .ser import *


# Create your views here.

class CateM(APIView):
    def get(self, request):
        # 获取一级分类
        cates = Category.objects.filter(parent_id__isnull=True).all()
        list = []

        # 循环获取二级
        for i in cates:
            dict = {}
            dict['id'] = i.id  # 一级ID
            dict['name'] = i.name  # 一级NAME
            two = i.subs.all()  # 通过一级反查询二级数据
            twolist = []
            # 循环二级获取三级
            for j in two:
                twodict = {}
                twodict['id'] = j.id  # 二级ID
                twodict['name'] = j.name  # 二级NAME
                three = j.subs.all()  # 通过二级反查询三级数据
                # 序列化器转成JSon的
                ser = CateSer(three, many=True)
                twodict['subs'] = ser.data  # 把三级数据添加给二级字典
                twolist.append(twodict)  # 再添加到二级列表
            dict['subs'] = twolist  # 把二级和三级数据加到一级字典
            list.append(dict)  # 再添加给一级列表
        goodslist = []
        # 循环一级
        for j in cates:
            dict1 = {}
            dict1['id'] = j.id
            dict1['name'] = j.name
            dict1['pic'] = str(j.pic)
            # 获取二级
            twos = j.subs.all()
            twoser = CateSer(twos, many=True)
            dict1['two'] = twoser.data
            # 获取三级
            threes = Category.objects.filter(top_parent=j.id, level=3).all()
            threeser = CateSer(threes, many=True)
            dict1['three'] = threeser.data
            # 获取商品
            sorted = request.GET.get('sorted')
            topid = request.GET.get('topid')
            goods = Goods.objects.filter(category1_id=j.id, home_show=1).all()

            if sorted:
                if int(topid) == int(j.id):
                    goods = Goods.objects.filter(category1_id=j.id, home_show=1).order_by(sorted).all()
            ser = GoodSer(goods, many=True)
            dict1['goods'] = ser.data
            goodslist.append(dict1)
        return Response({'code': 200, 'catelist': list, 'goodlist': goodslist})


class GoodsM(APIView):
    def get(self, request):
        id = request.GET.get('id')
        good = Goods.objects.filter(id=id).first()
        ser = GoodSer(good)
        return Response({'code': 200, 'list': ser.data})

    def post(self, request):
        userid = request.data.get('user')
        goodid = request.data.get('good')
        number = request.data.get('number')
        cart = Cart.objects.filter(user_id=userid, good_id=goodid).first()
        if cart:
            cart.number += number
            cart.save()
            return Response({'code': 200})
        else:
            # Cart.objects.create(user_id=userid, good_id=goodid, number=number)
            ser = CartSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'code': 200})
            else:
                print(ser.errors)
                return Response({'code': 10010})

    def put(self, request):
        id = request.GET.get('id')
        num = int(request.GET.get('num'))
        type = int(request.GET.get('type'))
        cart = Cart.objects.filter(id=id).first()
        if type == 1:
            cart.number += 1
        elif type == 2:
            cart.number -= 1
        elif type == 3:
            cart.number = num
        cart.save()
        return Response({'code': 200})


class CartM(APIView):
    def get(self, request):
        userid = request.GET.get('userid')
        cart = Cart.objects.filter(user_id=userid).all()
        ser = ShowCartSer(cart, many=True)
        allmoney = 0
        allnum = 0
        all_ischeck = True
        all_count = 0
        for i in ser.data:
            if i['is_check'] == True:
                allmoney += int(i['number']) * float(i['good']['price'])
                allnum += int(i['number'])
            if i['is_check'] == False:
                all_ischeck = False
            all_count += int(i['number'])

        return Response(
            {'code': 200, 'list': ser.data, 'all_count': all_count, 'allmoney': allmoney, 'all_ischeck': all_ischeck,
             'allnum': allnum})

    def delete(self, request):
        id = request.GET.get('id')
        Cart.objects.filter(id=id).delete()
        return Response({'code': 200})

    def put(self, request):
        id = request.GET.get('id')
        cart = Cart.objects.filter(id=id).first()
        if cart.is_check == True:
            cart.is_check = False
            cart.save()
        else:
            cart.is_check = True
            cart.save()
        return Response({'code': 200})

    def post(self, request):
        userid = request.data.get('user')
        all_ischeck = request.data.get('all_ischeck')
        if all_ischeck == True:
            Cart.objects.filter(user_id=userid).update(is_check=True)
        else:
            Cart.objects.filter(user_id=userid).update(is_check=False)
        return Response({'code': 200})


import datetime
import random
from user.ser import ShowAddSer
from django.db import transaction


class Order(APIView):

    def get(self, request):
        user = request.GET.get('userid')
        cart = Cart.objects.filter(user_id=user, is_check=True).all()
        ser = ShowCartSer(cart, many=True)
        allmoney = 0
        allnum = 0
        for i in ser.data:
            if i['is_check'] == True:
                allmoney += int(i['number']) * float(i['good']['price'])
                allnum += int(i['number'])
        return Response({'code': 200, 'list': ser.data, 'allmoney': allmoney, 'allnum': allnum})

    @transaction.atomic()
    def post(self, request):
        userid = request.data.get('userid')
        addressid = request.data.get('addressid')
        # 支付方式
        paytype = request.data.get('paytype')
        cart = Cart.objects.filter(user_id=userid, is_check=True).all()
        ser = ShowCartSer(cart, many=True)
        # 订单号
        order_no = datetime.datetime.strftime(datetime.datetime.now(), '%Y%M%D%H%M%S') + str(userid) + str(
            random.randint(100000, 999999))
        print(order_no)
        # 地址
        dizhi = Address.objects.filter(id=addressid).first()
        dizhi1 = ShowAddSer(dizhi)
        dizhis = dizhi1.data

        address = str(dizhis['province']['name']) + ' ' + str(dizhis['city']['name']) + ' ' + str(
            dizhis['area']['name']) + ' ' + str(
            dizhis['address']) + ' ' + str(dizhis['receive']) + ' ' + str(dizhis['mobile'])
        # 总金额
        total_amount = 0
        for i in ser.data:
            total_amount += int(i['number']) * float(i['good']['price'])

        data1 = {'order_no': order_no, 'user': userid, 'address': address, 'total_amount': total_amount,
                 'pay_method': paytype}
        # 使用序列化器添加
        sid = transaction.savepoint()
        try:
            oser = OrderSer(data=data1)
            if oser.is_valid():
                oser.save()
                # 生成订单详情
                for i in ser.data:
                    orderdata = {'order': order_no, 'goods': i['good']['id'], 'goodsname': i['good']['name'],
                                 'images': i['good']['pic'], 'count': i['number'], 'price': i['good']['price'],
                                 'user': userid}
                    dser = DOrderSer(data=orderdata)
                    if dser.is_valid():
                        dser.save()
            Cart.objects.filter(user_id=userid, is_check=True).delete()
            transaction.savepoint_commit(sid)
            return Response({'code': 200, 'total_amount': total_amount, 'order_no': order_no})
        except:
            transaction.savepoint_rollback(sid)
            return Response({'code': 20010})


class GetOrder(APIView):
    def get(self, request):
        userid = request.GET.get('userid')
        order = OrderDetail.objects.filter(user=userid).all()
        ser = DOrderSer(order, many=True)
        return Response({'code': 200, 'list': ser.data})


# import json
#
# from utils.comm import *
#
# class Buy(APIView):
#     def post(self, request):
#         userid = request.data.get('userid')
#         goods_id = request.data.get('goods_id')
#         conn = get_redis()
#         key = 'cart_' + userid
#         cart = conn.hget(key, goods_id)
#         if cart:
#             conn.hincrby(key, goods_id, 1)
#         else:
#             conn.hset('cart_' + userid, goods_id, 1)
#         return Response('ok')
#
#     def get(self, request):
#         userid = request.GET.get('userid')
#         conn = get_redis()
#         key = 'cart_' + str(userid)
#         carts = conn.hgetall(key)
#         data = ''
#         list = []
#         sum = 0
#         tmoney = 0
#         t_count = 0
#         selected_all = True
#         if carts:
#
#             selectedlist = conn.smembers('select_cart_%userid' % int(userid))
#
#             for k, v in carts.items():
#                 sum += int(v)
#                 goods = Goods.objects.filter(id=k).first()
#
#                 dict = {}
#                 dict['id'] = goods.id
#                 dict['name'] = goods.name
#                 dict['price'] = goods.price
#                 dict['image'] = 'http://localhost:8000/upload/' + str(goods.pic)
#                 dict['count'] = v
#                 if k in selectedlist:
#                     tmoney += int(v) * goods.price
#                     dict['selected'] = True
#                     t_count += int(v)
#                 else:
#                     dict['selected'] = False
#                     selected_all = False
#                 list.append(dict)
#
#         return Response({"code": 200, 'carts': list, 'total': sum, 'tmoney': tmoney, 't_count': t_count,
#                          'selected_all': selected_all})
#
#
# class SelectAll1(APIView):
#     def get(self, request):
#         conn = get_redis()
#         selected = request.GET.get('selected')
#         userid = request.GET.get('userid')
#         key = 'cart_' + str(userid)
#         carts = conn.hgetall(key)
#
#         if selected == 'false':
#             conn.srem('select_cart_%userid' % int(userid), *carts.keys())
#         else:
#             conn.sadd('select_cart_%userid' % int(userid), *carts.keys())
#         return Response({'code': 200})
#
#     def post(self, request):
#         conn = get_redis()
#         selected = request.data.get('flag')
#         userid = request.data.get('userid')
#         id = request.data.get('id')
#
#         key = 'cart_' + str(userid)
#         carts = conn.hgetall(key)
#         print(selected)
#         if selected == False:
#             conn.srem('select_cart_%userid' % int(userid), id)
#         else:
#             conn.sadd('select_cart_%userid' % int(userid), id)
#         return Response({'code': 200})
#
#     def put(self, request):
#         conn = get_redis()
#         userid = request.data.get('userid')
#         id = request.data.get('id')
#         type = request.data.get('type')
#         key = 'cart_' + str(userid)
#         if type == 1:
#             conn.hincrby(key, id, 1)
#         elif type == 2:
#             count = conn.hget(key, id)
#             if int(count) > 1:
#                 conn.hincrby(key, id, -1)
#             else:
#                 return Response({'code': 400})
#         elif type == 3:
#             count = int(request.data.get('count'))
#             if count > 0:
#                 conn.hset(key, id, count)
#             else:
#                 return Response({'code': 400})
#         return Response({'code': 200})
#
#     # 删除
#     def delete(self, request):
#         conn = get_redis()
#         userid = request.GET.get('userid')
#         id = request.GET.get('id')
#         print(userid)
#         print(id)
#         conn.hdel('cart_' + str(userid), id)
#         return Response({'code': 200})
